<?php

namespace app\common\model;

//抖音功能
use app\admin\model\DouyinAuth;
use app\admin\model\MeituanAuth;
use think\Log;

class DouyinLogic
{

    //HTTP POST 方法统一使用contentType 为“application/x-www-form-urlencoded”
//    private static $contentType = "application/x-www-form-urlencoded";
    private static $contentType = "application/json";

    /**
     * 获取抖音商家授权token
     * @param $app_key 应用key
     * @param $app_secret 应用密钥
     * 文档地址:
     * https://partner.open-douyin.com/docs/resource/zh-CN/dop/develop/openapi/account-permission/client-token
     * }
     */
    public static function GetAuthToken($app_key, $app_secret)
    {
        //使用fastadmin的http请求类 admin/extend/fast/Http.php
        $http = new \fast\Http();
        $url = "https://open.douyin.com/oauth/client_token/"; // 正式环境
//        $url = "https://open-sandbox.douyin.com/oauth/client_token/";// 沙河环境
        $params = [
            'client_key' => $app_key,
            'client_secret' => $app_secret,
            'grant_type' => 'client_credential',
        ];

        $headers = [
            'Content-Type' => self::$contentType,
        ];
        $result = $http->post($url, $params, [CURLOPT_HTTPHEADER => $headers]);
        $result = json_decode($result, true);
        $expire_time = time() + $result['data']['expires_in'];
        //过期时间戳转换为日期
        $session_expire_time = date('Y-m-d H:i:s', $expire_time);
        $update_data = [
//            'scope' => $result['data']['scope'],
//            'refresh_session' => $result['data']['refresh_token'],
            'session' => $result['data']['access_token'],
            'session_expire_time' => $session_expire_time,
            'session_status' => 1,
            'last_refresh_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s'),
        ];
        DouyinAuth::where('app_key', $app_key)->where('app_key', $app_key)->update($update_data);
        return $result['data'];
    }

    // 抖音验券准备
    public static function Preparation($appid, $appSecret, $encrypted_data, $code, $token)
    {
        $douyin = new Douyin($appid, $appSecret);
        $result = $douyin->prepareCertificate($token, $encrypted_data, $code);
        if ($result['data']['error_code'] == 2190008) {
//            $token =  $douyin->get_client_token();
            $token = self::GetAuthToken($appid, $appSecret)['access_token'];
            $result = $douyin->prepareCertificate($token, $encrypted_data, $code);
        }
        self::writeSucLog('抖音验券准备' . json_encode($result, JSON_UNESCAPED_UNICODE));
        return $result['data'];
    }

    // 抖音核销券
    public static function VerifyCoupon($appid, $appSecret, $poi_id, $client_token, $encrypted_data, $code)
    {
        $douyin = new Douyin($appid, $appSecret, $poi_id);
        $res = $douyin->prepareCertificate($client_token, $encrypted_data, $code);
        if ($res['data']['error_code'] == 2190008) {
            $client_token = self::GetAuthToken($appid, $appSecret)['access_token'];
            $res = $douyin->prepareCertificate($client_token, $encrypted_data, $code);
        }
        $v = $res['data']['verify_token'];
        $code = $res['data']['certificates'][0]['encrypted_code'];
        $result = $douyin->verifyCoupon($v, $client_token, $poi_id, [$code]);
        self::writeSucLog('抖音核销券' . json_encode($result, JSON_UNESCAPED_UNICODE));
        return ['res' => $result['data'], 'goods' => $res['data']];
    }

    // 抖音撤销券
    //verify_id 代表券码一次核销的唯一标识（验券时返回）(次卡撤销多次时请填0)
    //certificate_id 代表一张券码的标识（验券时返回）
    public static function Revoke($appid, $appSecret, $verify_id, $certificate_id, $token)
    {
        $douyin = new Douyin($appid, $appSecret);
        $result = $douyin->revokeCoupon($verify_id, $certificate_id, $token);
        if ($result['data']['error_code'] == 2190008) {
            $token = self::GetAuthToken($appid, $appSecret)['access_token'];
            $result = $douyin->revokeCoupon($verify_id, $certificate_id, $token);
        }
        self::writeSucLog('抖音撤销券' . json_encode($result, JSON_UNESCAPED_UNICODE));
        return $result['data'];
    }

    // 写入日志
    public static function writeSucLog($content)
    {
        $directory = './log/success/';
        $logFile = $directory . date('Ymd') . '.log';
        if (!is_dir($directory)) {
            mkdir($directory, 0777, true);
        }
        $content = date('Y-m-d H:i:s') . '： ' . $content . PHP_EOL;
        @file_put_contents($logFile, $content, FILE_APPEND);
    }
}